package com.czk.duration;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @Author:ChenZhangKun
 * @Date: 2022/7/9 15:50
 */
public class DurationDays {
    static String target = "2022-07-26";

    public static void main(String[] args) throws ParseException {
        System.out.println(toDays());

        calculateDaysGap(new Date(), new SimpleDateFormat("yyyy-MM-dd").parse("2022-07-26"));

        doSomething();
    }

    public static long toDays() {
        LocalDate target = LocalDate.parse(DurationDays.target);
        LocalDate now = LocalDate.now();
        long abs = Math.abs(target.toEpochDay() - now.toEpochDay());
        return abs;
    }

    public static void calculateDaysGap(Date start, Date end) {
        final long ONE_DAY_MILLIS = 1000L * 60 * 60 * 24;
        // 此处要注意，去掉时分秒的差值影响，此处采用先换算为天再相减的方式
        long gapDays = Math.abs(end.getTime() / ONE_DAY_MILLIS - start.getTime() / ONE_DAY_MILLIS);
        System.out.println(gapDays);
    }

    public static void doSomething() {
        // 记录开始时间戳
        Instant start = Instant.now();
        // do something ...
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 计算结束时间戳
        Instant end = Instant.now();

        // 计算相差的毫秒数
        System.out.println(Duration.between(start, end).toMillis());
    }

}
